<?php

namespace QF\Rbac;

use Treenode;

class Route extends \TreeModel {
    
    static public $table = "rbac_route";
    protected $_fillable = array(
        'sort' => 'int',
        'parent_id' => 'int',
        'title' => 'str',
        'url' => 'str',
        'depth' => 'int',
        'parents' => 'str',
        'parents_reverse' => 'str',
    );
    
    /**
     * 获取已授权的权限树
     * @return \Treenode
     */
    public function getAuthedTree($perm_keys = 'all') {
        if ($perm_keys == 'all') {
            $rows = Db()->getAll(static::$table)->order('depth, parent_id, sort, id')->result();
        } else {
            if (!$perm_keys) {
                return array();
            }
            $rows = Db()->getAll(static::$table)->where(array('id' => array('in' => $perm_keys)))->whereOr(array('depth' => 0))->order('depth, parent_id, sort, id')->result();
        }

        $nav = new Treenode();

        foreach ($rows as $row) {
            if ($parent = $nav->getNodeByKey($row['parent_id'])) {
                $parent->addChildNode(new Treenode($row['id'], $row['title'], $row));
            } else {
                $nav->addChildNode(new Treenode($row['id'], $row['title'], $row));
            }
        }

        $sub = $nav->getChildNodes();
        return $sub[0]->getChildNodes();
    }

    /**
     * 获取带checked属性的权限树
     * @return \Treenode
     */
    public function getCheckedTree($route_ids = 'all', $indent = '└─ ') {
        $rows = Db()->getAll(static::$table)->order('depth, parent_id, sort, id')->result();

        $tree = new Treenode();

        foreach ($rows as $row) {
            
            if ($route_ids == 'all' || in_array($row['id'], $route_ids)) {
                $row['checked'] = 'checked="checked"';
            }

            if ($parent = $tree->getNodeByKey($row['parent_id'])) {
                if ($indent) {
                    $repeat_str = $parent->getLevel() - 1 ? str_repeat('&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;', $parent->getLevel() - 2) . $indent : '';
                    $row['title'] = $repeat_str . $row['title'];
                }
                $row['css'] = $parent->getData('css') . ' route_' . $row['id'];
                $row['parent_css'] = $parent->getData('css');
                $parent->addChildNode(new Treenode($row['id'], $row['title'], $row));
            } else {
                $row['css'] = 'route_' . $row['id'];
                $row['parent_css'] = '';
                $tree->addChildNode(new Treenode($row['id'], $row['title'], $row));
            }
        }

        $sub = $tree->getChildNodes();
        return $sub[0]->getChildNodes();
    }

}
